package cn.sixmillions.wiki.common.handler;

import cn.sixmillions.wiki.common.enums.ResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @description: 基础异常处理类
 * @author: sixmillions
 * @since: 2021/06/04
 **/
@Slf4j
@RestControllerAdvice
public class BaseExceptionHandler {
    /**
     * 总异常
     */
    @ExceptionHandler(Exception.class)
    public R<Object> exceptionHandler(Exception ex, HttpServletRequest request) {
        log.error("url:{},| errMsg:{}", request.getRequestURI(), ex.getMessage(), ex);
        return R.fail(ResultCodeEnum.INTERNAL_SERVER_ERROR, "none", ex.getMessage());
    }

    /**
     * 自定义系统异常异常捕捉处理
     */
    @ExceptionHandler(ServiceException.class)
    public R<Object> serviceExceptionHandler(ServiceException ex, HttpServletRequest request) {
        log.error("url:{},| errMsg:{}", request.getRequestURI(), ex.getMessage());
        return R.fail(ResultCodeEnum.FAILURE, ex.getErrorCode(), ex.getMessage());
    }

    /**
     * 系统发生转型异常捕捉处理
     */
    @ExceptionHandler(ClassCastException.class)
    public R<Object> paramExceptionHandler(ClassCastException ex, HttpServletRequest request) {
        log.error("url:{},|errMsg:{}", request.getRequestURI(), ex.getMessage());
        return R.fail(ex.getMessage());
    }
}
